package com.oktest.measure.ui.fragment.login

import android.os.Bundle
import com.cali.common.kt.countDown
import com.cali.common.kt.jsonBody
import com.cali.common.kt.value
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.http.RetrofitManagement
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.http.Api
import com.oktest.measure.kt.API_SUCCESS_CODE
import com.oktest.measure.kt.resultTryContext
import kotlinx.android.synthetic.main.fragment_verify_code.*
import kotlinx.coroutines.launch

/**
 * @Author hhh
 * @Date 2020/11/19
 */
class VerifyCodeFragment:BaseFragment() {
    override fun getLayoutId() = R.layout.fragment_verify_code

    override fun initData(savedInstanceState: Bundle?) {
        initTitle()
        tvVerify.setOnClickListener {
            verify()
        }
        tvObtainCode.setOnClickListener {
            obtainCode()
        }
    }

    private fun initTitle() {
        toolbarHelper?.apply {
            setTitleText("验证手机号")
        }
    }

    override fun hasToolbar(): Boolean {
        return true
    }

    private fun obtainCode() = launch {
        val phone = etPhone.value()
        if (phone.isEmpty()) {
            toast("手机号不能为空")
            return@launch
        }
        tvCountDown.countDown(60,"获取验证码")
        val codeResult = resultTryContext {
            RetrofitManagement.instance.getService(Api::class.java)
                .code(phone).execute().body()
        }
        if (codeResult.code == API_SUCCESS_CODE) {
            toast("请注意查收验证码")
        } else {
            error(codeResult)
        }
    }

    private fun verify() = launch{
        val code = etVerifyCode.value()
        if (code.isEmpty()) {
            toast("验证码不能为空")
            return@launch
        }
        val map = hashMapOf("mobile" to etPhone.value(), "code" to code)
        val body = map.jsonBody()
        val validResult = resultTryContext {
            RetrofitManagement.instance.getService(Api::class.java)
                .validCode(body).execute().body()
        }
        if (validResult.code == API_SUCCESS_CODE) {
            MyApp.memberId = validResult.data?.memberId?:""
            start(ResetFragment())
            pop()
        } else {
            error(validResult)
        }
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }
}